import { createSlice } from '@reduxjs/toolkit';

// 检查token是否有效（简单检查，实际应用中可能需要更复杂的验证）
const validateToken = (token) => {
  // 如果token为null、undefined、空字符串或'null'字符串，则认为无效
  return token && token !== 'null' && token !== 'undefined' && token.length > 10;
};

// 获取localStorage中的token，并验证其有效性
const storedToken = localStorage.getItem('token');
const initialToken = validateToken(storedToken) ? storedToken : null;

// 如果token无效，清除localStorage中的token
if (!initialToken && storedToken) {
  localStorage.removeItem('token');
}

const userSlice = createSlice({
  name: 'user',
  initialState: {
    userInfo: null,
    token: initialToken,
  },
  reducers: {
    setUserInfo: (state, action) => {
      state.userInfo = action.payload;
    },
    setToken: (state, action) => {
      state.token = action.payload;
      localStorage.setItem('token', action.payload);
    },
    logout: (state) => {
      state.userInfo = null;
      state.token = null;
      localStorage.removeItem('token');
    },
  },
});

export const { setUserInfo, setToken, logout } = userSlice.actions;
export default userSlice.reducer;
